import requestUtil from '../../baseRequest.js'
import requestUrls from '../../requestUrl.js'
import commonUtils from '../../utils/util.js'
import { $Message } from '../../components/base/index'
let openid = wx.getStorageSync('openid')
let h;
let w;
wx.getSystemInfo({
  success: function (res) {
    h = res.windowHeight - 30
    w = res.windowWidth
  },
})
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mainTruckUrl:requestUrls.baseImagePrefixUrl+'/f28500f4-c5d5-480d-86c6-c674eeac2c55.png',
    truckCenterList: [],
    openId: openid,
    currentTab: 'TRUCK_CENTER',
    publishSide: 'TRUCK_CENTER',
    carImageList: [
      { id: '1', imageUrl: '/assets/truck_01.png', maxWeight: 139000, truckLength: '12.4', truckWidth: '11.5', truckHeight: '11.5', maxVolume: 166.5 },
      { id: '2', imageUrl: '/assets/truck_02.png', maxWeight: 9.8, truckLength: '2.7', truckWidth: '1.6', truckHeight: '1.6', maxVolume: 6.5 },
      { id: '3', imageUrl: '/assets/truck_03.png', maxWeight: 9.8, truckLength: '2.7', truckWidth: '1.6', truckHeight: '1.6', maxVolume: 6.5 },
      { id: '4', imageUrl: '/assets/truck_01.png', maxWeight: 139000, truckLength: '12.4', truckWidth: '11.5', truckHeight: '11.5', maxVolume: 166.5 },
      { id: '5', imageUrl: '/assets/truck_02.png', maxWeight: 9.8, truckLength: '2.7', truckWidth: '1.6', truckHeight: '1.6', maxVolume: 6.5 },
      { id: '6', imageUrl: '/assets/truck_03.png', maxWeight: 9.8, truckLength: '2.7', truckWidth: '1.6', truckHeight: '1.6', maxVolume: 6.5 },
      { id: '7', imageUrl: '/assets/truck_01.png', maxWeight: 139000, truckLength: '12.5', truckWidth: '11.5', truckHeight: '11.5', maxVolume: 166.5 },
    ],
    truckTypeList: [
      "厢式密封", "厢式尾板", "高栏",
      "低栏", "平板", "冷藏车", "开顶箱车",
    ],
    carItem: {},
    x: w,
    movable_height: h - 380,
    customItem: '全部',
    fromProvinceId: '',
    fromCityId: '',
    fromCountyId: '',
    fromProvinceName: '',
    fromCityName: '',
    fromCountyName: '',
    toProvinceId: '',
    toCityId: '',
    toCountyId: '',
    toProvinceName: '',
    toCityName: '',
    toCountyName: '',
    currentNavId: '',
    pagination: {
      pageSize: 5,
      pageNum: 1,
      total: 0
    },
    bottomMenuId: 'wdfb',
    needOpt: 'N'
  },
  changeNavTab(event) {
    this.setData({
      currentNavId: event.target.dataset.current,
      carItem: this.data.carImageList[event.target.dataset.current],
    })
  },
  showErrorMessage(msg) {
    $Message({
      content: msg,
      type: 'error'
    })
  },
  //切换车主/货主标签
  changeHeadTab: function (event) {
    let targetTab = event.currentTarget.dataset.tabname;
    this.setData({
      currentTab: targetTab,
      publishSide: targetTab,
      bottomMenuId: 'wdfb',
      truckCenterList: [],
      pagination: {
        pageSize: 5,
        pageNum: 1,
        total: 0
      },
    }),
      this.getPage();
  },

  //跳转到货源大厅
  linkToOrderCenter: function () {
    this.checkUserInfoRole(() => {
      wx.navigateTo({
        url: '/pages/orderCenter/index?publishSide=' + this.data.publishSide
      })
    })
  },

  //跳转到运单中心页面
  linkToTruckCenterList: function () {
    this.checkUserInfoRole(() => {
      let url = '';
      if (this.data.currentTab === 'TRUCK_CENTER') {
        url = '/pages/truckCenter/index?publishSide=' + this.data.publishSide
      } else if (this.data.currentTab === 'ORDER_CENTER') {
        url = '/pages/truckCenter/index?publishSide=' + this.data.publishSide
          + '&fromProvinceName=' + this.data.fromProvinceName
          + '&fromCityName=' + this.data.fromCityName
          + '&fromCountyName=' + this.data.fromCountyName
          + '&toProvinceName=' + this.data.toProvinceName
          + '&toCityName=' + this.data.toCityName
          + '&toCountyName=' + this.data.toCountyName
        //筛选条件去掉车型传入
        // + '&truckTypeName=' + this.data.truckTypeList[this.data.currentNavId]
      }
      wx.navigateTo({
        url: url
      })
    });
  },
  //跳转到运单页面
  linkToTruckCenter: function (event) {
    //存储的是关联信息ID
    let truckOrderId = event.currentTarget.dataset.truckcenterid;
    //如果为车主查看订单内容；则跳转到装货页面
    if (this.data.currentTab === 'TRUCK_CENTER') {
      this.data.truckCenterList.forEach(item => {
        if (item.id === truckOrderId) {
          if (this.data.bottomMenuId === 'wdfb') {
            wx.navigateTo({
              url: '/pages/truckCenter/detail?publishSide=' + this.data.publishSide + "&truckCenterId=" + truckOrderId
            })
          } else if (this.data.bottomMenuId === 'dwcl') {
            wx.navigateTo({
              url: '/pages/orderCenter/detail?publishSide=' + this.data.publishSide + "&otiId=" + item.oti_id
            })
          } else if (this.data.bottomMenuId === 'jxzdyd') {
            wx.navigateTo({
              url: '/pages/orderCenter/detail?publishSide=' + this.data.publishSide + "&otiId=" + item.truckOrderInfoId
            })
          }
          // if (item.statusId === '20') {

          // }else if (item.statusId === '30') {
          //   wx.navigateTo({
          //     url: '/pages/orderCenter/detail?publishSide=' + this.data.publishSide + "&truckCenterId=" + truckOrderId
          //   })
          // } else {
          //   if (item.step === '2') {
          //     wx.navigateTo({
          //       url: '/pages/transportConfirm/complete/index?confirmId=' + item.confirmId
          //     })
          //   } else {
          //     wx.navigateTo({
          //       url: '/pages/transportConfirm/stepTwo/index?truckOrderId=' + item.truckOrderInfoId + '&publishSide=' + this.data.publishSide
          //     })
          //   }
          // }
        }
      })
    }
    //如果是货主查看订单内容;则跳转到货物详情页面
    if (this.data.currentTab === 'ORDER_CENTER') {
      let id = '';
      this.data.truckCenterList.forEach(item => {
        if (item.id === truckOrderId) {
          if (this.data.bottomMenuId === 'wdfb') {
            wx.navigateTo({
              url: '/pages/orderCenter/detail?orderCenterId=' + truckOrderId + '&publishSide=ORDER_CENTER'
            })
          } else if (this.data.bottomMenuId === 'dwcl') {
            wx.navigateTo({
              url: '/pages/truckCenter/detail?publishSide=ORDER_CENTER&otiId=' + item.oti_id,
            })
          } else if (this.data.bottomMenuId === 'jxzdyd') {
            wx.navigateTo({
              url: '/pages/truckCenter/detail?publishSide=ORDER_CENTER&otiId=' + item.truckOrderInfoId,
            })
          }
        }
      })
    }
  },
  //跳转到发布车辆页面
  linkToTruckCenterAdd: function (event) {
    this.checkUserInfoRole(() => {
      if (this.data.currentTab === 'TRUCK_CENTER') {
        wx.navigateTo({
          url: '/pages/truckCenter/addv2'
        });
      }
      if (this.data.currentTab === 'ORDER_CENTER') {
        wx.navigateTo({
          url: '/pages/orderCenter/addv2'
        });
      }
    });

  },
  //修改出发地信息
  fromRegionChange: function (e) {
    const regionNameList = [...e.detail.value, "", "", ""];
    this.setData({
      fromProvinceName: regionNameList[0],
      fromCityName: regionNameList[1],
      fromCountyName: regionNameList[2],
    })
  },
  //修改目的地信息
  toRegionChange: function (e) {
    const regionNameList = [...e.detail.value, "", "", ""];
    this.setData({
      toProvinceName: regionNameList[0],
      toCityName: regionNameList[1],
      toCountyName: regionNameList[2],
    })
  },
  getPage: function () {
    this.checkUserInfoRole(() => {
      let statusIds = [];
      if (this.data.bottomMenuId === 'wdfb') {
        //我的发布：发布方为自己，状态为20
        statusIds = ['20'];
      } else if (this.data.bottomMenuId === 'dwcl') {
        //发布方为自己或申请方为自己
        statusIds = ['dwcl'];
      } else if (this.data.bottomMenuId === 'jxzdyd') {
        //进行中的运单：发布方为自己，状态为待装货，进行中
        statusIds = ['35', '40', '60'];
      }
      const formData = {
        openId: this.data.openId,
        criteria: {
          publishSide: this.data.publishSide,
          statusIds,
          searchType: 'homeV2',
        },
        pageDto: {
          ...this.data.pagination
        }
      }
      //查询是否存在待我处理的数据
      const dwclQuery = {
        openId: this.data.openId,
        criteria: {
          publishSide: this.data.publishSide,
          statusIds: ['dwcl'],
          searchType: 'homeV2',
        },
        pageDto: {
          pageSize: 5,
          pageNum: 1,
          total: 0
        }
      }
      requestUtil.postRequest(requestUrls.truckOrder.getHomeV2Page, dwclQuery, (res) => {
        if (!res.hasError) {
          const { list = [] } = res.result;
          if(list&&list.length>0){
            this.setData({
              needOpt:'Y',
            })
          }else{
            this.setData({
              needOpt:'N',
            })
          }
        }
      });
      requestUtil.postRequest(requestUrls.truckOrder.getHomeV2Page, formData, (res) => {
        if (!res.hasError) {
          const { list = [] } = res.result;
          console.log(list);
          let truckCenterList = [];
          if (list.length > 0) {
            list.forEach(item => {
              if (this.data.currentTab === 'TRUCK_CENTER') {
                if (this.data.bottomMenuId === 'dwcl') {
                  truckCenterList.push({
                    ...item,
                    freeBeginTime: commonUtils.formatDate(item.freeBeginTime, 'MM-dd hh'),
                    freeEndTime: commonUtils.formatDate(item.freeEndTime, 'MM-dd hh'),
                    statusName: item.orderCenter.statusName,
                    oti_id: item.orderTruckInfo.id,
                  })
                } else {
                  truckCenterList.push({
                    ...item,
                    freeBeginTime: commonUtils.formatDate(item.freeBeginTime, 'MM-dd hh'),
                    freeEndTime: commonUtils.formatDate(item.freeEndTime, 'MM-dd hh'),
                  })
                }
              } else if (this.data.currentTab === 'ORDER_CENTER') {
                if (this.data.bottomMenuId === 'dwcl') {
                  truckCenterList.push({
                    ...item,
                    loadingBeginTime: commonUtils.formatDate(item.loadingBeginTime, 'MM-dd hh'),
                    loadingEndTime: commonUtils.formatDate(item.loadingEndTime, 'MM-dd hh'),
                    statusName: item.truckCenter.statusName,
                    oti_id: item.orderTruckInfo.id,
                  })
                } else {
                  truckCenterList.push({
                    ...item,
                    loadingBeginTime: commonUtils.formatDate(item.loadingBeginTime, 'MM-dd hh'),
                    loadingEndTime: commonUtils.formatDate(item.loadingEndTime, 'MM-dd hh'),
                  })
                }
              }
            })
          }
          this.setData({
            truckCenterList: this.data.truckCenterList.concat(truckCenterList),
            pagination: {
              ...this.data.pagination,
              total: res.result.total
            }
          })
        }
      })
    });
  },
  //跳转到全部运单界面
  linkToTruckOrderList: function () {
    this.checkUserInfoRole(() => {
      wx.navigateTo({
        url: '/pages/orderTruck/listv2?publishSide=' + this.data.publishSide
      });
    });
  },
  //切换底部页签
  changebottommenu: function (event) {
    let menuId = event.currentTarget.dataset.menuid;
    this.setData({
      bottomMenuId: menuId,
      truckCenterList: [],
      pagination: {
        pageSize: 5,
        pageNum: 1,
        total: 0
      },
    })
    //根据货主/车主页签和下部页签发起请求，查询显示数据
    this.getPage();
  },
  checkUserInfoRole(callback) {
    if (!this.data.userInfo) {
      setTimeout(() => {
        this.getUserInfo();
        this.checkUserInfoRole(callback);
      }, 100)
    } else {
      let userInfo = getApp().globalData.userInfo;
      this.setData({
        userInfo,
      })
      console.log({'userInfo':this.data.userInfo})
      if (this.data.userInfo) {
        const {userInfo} = this.data;
          if(userInfo.isMember && parseInt(userInfo.isMember)===0){
            //未获取微信授权的情况
            wx.showModal({
              title: '温馨提示',
              content: '您还未完成注册，请完成注册后重试',
              confirmText: '前往注册',
              success: res => {
                if (res.confirm) {
                  wx.switchTab({
                    url: '/pages/user/personal/index'
                  })
                }
              }
            })
          }else if(userInfo.isRegister && parseInt(userInfo.isRegister)===0){
            //获取微信授权，但没注册成为注册用户的情况
            wx.showModal({
              title: '温馨提示',
              content: '您还未完成注册，请完成注册后重试',
              confirmText: '前往注册',
              success: res => {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/user/registerUser/index'
                  })
                }
              }
            })
          }else if(userInfo.isDriver && parseInt(userInfo.isDriver)===-1){
            //注册用户完成，但没完成会员信息录入的情况
            wx.showModal({
              title: '温馨提示',
              content: '您还未完成司机认证，请完成认证后重试',
              confirmText: '前往认证',
              success: res => {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/user/memberRegister/before'
                  })
                }
              }
            })
          }else{
            callback()
          }
      } else {
        //查询不到信息的情况
        wx.showModal({
          title: '温馨提示',
          content: '您还未完成注册，请完成注册后重试',
          confirmText: '前往注册',
          success: res => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/user/personal/index'
              })
            }
          }
        })
      }
    }
  },
  getUserInfo() {
    let userInfo = getApp().globalData.userInfo;
    if (userInfo) {
      // wx.setStorageSync('openid', userInfo.openid);
      this.setData({
        userInfo: userInfo,
        openId: userInfo.openid,
      });

      // this.getPage();
    } else {
      setTimeout(() => {
        this.getUserInfo();
      }, 10)
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('onLoad');
    this.getUserInfo();
    this.setData({
      currentNavId: '0',
      carItem: this.data.carImageList[0],
      truckCenterList: [],
    });
    this.getPage();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

    // this.getUserInfo();
    // if (this.data.userInfo) {
    //   this.setData({
    //     truckCenterList:[],
    //   })
    //   this.getPage();
    // }
    this.setData({
      truckCenterList: [],
      pagination: {
        pageSize: 5,
        pageNum: 1,
        total: 0
      },
    })
    this.getPage();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { pageSize, pageNum, total } = this.data.pagination;
    if (pageSize * pageNum >= total) {
      this.showErrorMessage("已加载全部数据");
    } else {
      this.setData({
        pagination: {
          ...this.data.pagination,
          pageNum: pageNum + 1
        }
      });
      this.getPage();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})